using UnityEngine;
using System.Collections;

[AddComponentMenu("TagMachine/Tools/Timer")]
public class Timer : PauseSystem
{
	public bool StartOnAwake 	= true;

	public bool DestroyOnEnd	= false;
	public int RestartTimes		= 0;

	public float Duration		= 2.0f;
	public float CurrentTime	{ get; private set; }

	public delegate void TimerCallback ();
	public event TimerCallback TimerCallbackEvent;

	public float RemainingTime
	{
		get
		{
			return Duration - CurrentTime;
		}
	}

	private int m_RemainingRestart;

	// Use this for initialization
	void Start()
	{
		Restart();
		enabled 			= StartOnAwake;
	}

	public void Restart()
	{
		CurrentTime			= 0.0f;
		m_RemainingRestart 	= RestartTimes;
		enabled 			= true;
	}

	// Update is called once per frame
	void Update ()
	{
		CurrentTime += Time.deltaTime;

		if ( CurrentTime >= Duration )
		{
			End();
		}
	}

	void End()
	{
		if ( TimerCallbackEvent != null )
		{
			TimerCallbackEvent();
		}

		--m_RemainingRestart;

		if ( DestroyOnEnd )
		{
			Destroy( this );
		}
		else if ( RestartTimes <= 0 || m_RemainingRestart > 0 )
		{
			Restart();
		}
		else
		{
			enabled = false;
		}
	}
	
	public static string ComputeTimeFromSeconds( float _Time )
	{
		int RemainingSeconds = (int)_Time;
		int RemainingMinutes = RemainingSeconds / 60;
		
		RemainingSeconds = RemainingSeconds % 60;
		
		if ( RemainingSeconds < 10 )
		{
			return "" + RemainingMinutes + ":0" + RemainingSeconds;
		}
		else
		{
			return "" + RemainingMinutes + ":" + RemainingSeconds;
		}
	}
}

